package com.mrjy.aiui.bo;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mrjy.aiui.dao.IAiuiRecordInfoDao;
import com.mrjy.aiui.dao.IAiuiUserSessionInfoDao;
import com.mrjy.aiui.dto.AiuiRecordInfoDTO;
import com.mrjy.aiui.dto.ChatMessageDTO;
import com.mrjy.aiui.util.IatUtils;
import com.mrjy.aiui.util.MessageUtils;
import com.mrjy.aiui.util.SmsTypeEnum;
import com.mrjy.common.entity.AiuiRecordInfo;
import com.mrjy.common.entity.AiuiUserSessionInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.maintain.dto.TeacherInfoDTO;

@Service("aiuiBo")
public class AiuiBo implements IAiuiBo {
	@Resource
	private IAiuiRecordInfoDao aiuiRecordInfoDao ;
	@Autowired
	private SolrServerClient solrServerClient;
	@Autowired
	private IAiuiUserSessionInfoDao aiuiUserSessionInfoDao ;
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Object textSemantic(String userId, String scene, String txt ,String smsType, String flag, String sessionId) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(flag)){
			if("0".equals(flag)){//会话开始
				UUID uuid = UUID.randomUUID();
				sessionId = uuid.toString().replace("-", "");
				AiuiUserSessionInfo ausi = new AiuiUserSessionInfo();
				ausi.setSessionId(sessionId);
				ausi.setUserId(StringUtils.isNotBlank(userId) == true ? Integer.valueOf(userId) : 0 );
				ausi.setCreateTime(new Timestamp(System.currentTimeMillis()));
				ausi.setStartTime(new Timestamp(System.currentTimeMillis()));
				aiuiUserSessionInfoDao.insert(ausi);
			}else if("1".equals(flag)){
				if(StringUtils.isNotBlank(sessionId)){
					AiuiUserSessionInfo ausi = new AiuiUserSessionInfo();
					ausi.setSessionId(sessionId);
					ausi.setUserId(StringUtils.isNotBlank(userId) == true ? Integer.valueOf(userId) : 0);
					AiuiUserSessionInfo ai = aiuiUserSessionInfoDao.selectByuserIdAndSessionId(ausi);
					if(ai != null){
						ai.setEndTime(new Timestamp(System.currentTimeMillis()));
						Long time = (System.currentTimeMillis() - ai.getStartTime().getTime())/(1000*60);
						ai.setDuration(time+"min");
						aiuiUserSessionInfoDao.updateById(ai);
					}else{
						UUID uuid = UUID.randomUUID();
						sessionId = uuid.toString().replace("-", "");
						ai = new AiuiUserSessionInfo();
						ai.setSessionId(sessionId);
						ai.setUserId(StringUtils.isNotBlank(userId) == true ? Integer.valueOf(userId) : 0 );
						ai.setCreateTime(new Timestamp(System.currentTimeMillis()));
						ai.setEndTime(new Timestamp(System.currentTimeMillis()));
						aiuiUserSessionInfoDao.insert(ausi);
					}
				}
				//不请求科大讯飞，不记录聊天记录，直接返回
				return null ;
			}
		}
		//记录用户的提问记录
		AiuiRecordInfo aInfo = new AiuiRecordInfo() ;
		aInfo.setUserId(StringUtils.isNotBlank(userId) == true ? Integer.valueOf(userId) : 0 );
		aInfo.setContent(txt);
		aInfo.setSmsType(SmsTypeEnum.USER_ASK.getSmsType());
		aInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
		aInfo.setSessionId(sessionId);
		aiuiRecordInfoDao.insert(aInfo);
		
		if(StringUtils.isBlank(userId)){
			map.put("err_code", "401") ;
			map.put("err_msg", "用户的id不能为空") ;
			return map ;
		}
		
		String result = IatUtils.textSemantic(userId, scene, txt) ;
		System.out.println(result);
		JSONObject jsonObj = JSONObject.fromObject(result) ;
		//AiuiBaseDTO baseDTO = (AiuiBaseDTO) JSONObject.toBean(jsonObj, AiuiBaseDTO.class);
		if(jsonObj == null){
			map.put("err_code", "402") ;
			map.put("err_msg", "") ;
			return map ;
		}
		if(null == jsonObj.get("data")){
			map.put("err_code", jsonObj.get("code")) ;
			map.put("err_msg", jsonObj.get("desc")) ;
			return map ;
		}
		if(!"00000".equals(jsonObj.get("code"))){//请求失败
			map.put("err_code", jsonObj.get("code")) ;
			map.put("err_msg", jsonObj.get("desc")) ;
			return map ;
		}
		List<ChatMessageDTO> messageList = new ArrayList<ChatMessageDTO>() ;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		JSONObject baseObj = jsonObj.getJSONObject("data") ;
		if("0".equals(baseObj.get("rc").toString())){//解析成功
			String service =  baseObj.getString("service");
			JSONObject answer = baseObj.getJSONObject("answer") ;//回复内容实体
			
			String content = "" ;
			String sms_type = "" ;
			String keywords = "" ;
			
			if(IatUtils.MRJY_JINENG_NAME.equals(service)){ // 自定义技能的回答
				if(answer != null){
					JSONObject chat = (JSONObject) answer.get("text") ;
					sms_type = chat.getString("smsType") ;
					content = chat.getString("content");
					keywords =chat.getString("keywords") ; 
					String lable = chat.getString("lable") ;
					
					//smsType 取值问题，如果科大那边传回来有值，然后前端也有传值进来，看看那个值就取哪个
					if(StringUtils.isNotBlank(sms_type)){
						if(StringUtils.isNotBlank(smsType)){
							smsType =  Integer.valueOf(sms_type) > Integer.valueOf(smsType) ? sms_type : (Integer.valueOf(smsType) + 1)+"" ;
						}else {
							smsType = sms_type ;
						}
						if("0".equals(smsType)){ // 推送文字回答
							try {
								Map<String , Object> rMap = solrServerClient.doRecommend(lable.toString(), "22", 1, 1, false) ;
								List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
								if(solrList!= null && solrList.size() > 0){
									SolrEntity se = solrList.get(0);
									if(se != null){
										MessageUtils.textMessageTemp(se, messageList);
									}
								}else {//没有文字回答，自动推送语音
									rMap = solrServerClient.doRecommend(lable.toString(), "21", 1, 1, false) ;
									solrList = (List<SolrEntity>) rMap.get("rows") ;
									if(solrList!= null && solrList.size() > 0){
										smsType = SmsTypeEnum.AUDIO_ANSWER.getSmsType() ;
										SolrEntity se = solrList.get(0);
										if(se != null){
											MessageUtils.audioMessageTemp(se, messageList);
										}
									}else {//没有语音，自动推送视频
										rMap = solrServerClient.doRecommend(lable.toString(), "0", 1, 1, false) ;
										solrList = (List<SolrEntity>) rMap.get("rows") ;
										if(solrList!= null && solrList.size() > 0){
											smsType = SmsTypeEnum.VIDEO_ANSWER.getSmsType() ;
											SolrEntity se = solrList.get(0);
											if(se != null){
												MessageUtils.videoMessageTemp(se, messageList);
											}
										}else{//没有视频就推送明师主页
											//暂时
											rMap = solrServerClient.doRecommend("大山笑长", "1", 1, 1, false) ;
											solrList = (List<SolrEntity>) rMap.get("rows") ;
											if(solrList!= null && solrList.size() > 0){
												smsType = SmsTypeEnum.TEACER_ANSWER.getSmsType() ;
												SolrEntity se = solrList.get(0);
												if(se != null){
													MessageUtils.teacherMessageTemp(se, messageList);
												}
											}
										}
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else if("1".equals(smsType)){//推送语音
							try {
								Map<String, Object> rMap = solrServerClient.doRecommend(lable.toString(), "21", 1, 1, false);
								List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
								if(solrList!= null && solrList.size() > 0){
									smsType = SmsTypeEnum.AUDIO_ANSWER.getSmsType() ;
									SolrEntity se = solrList.get(0);
									if(se != null){
										MessageUtils.audioMessageTemp(se, messageList);
									}
								}else {//没有语音，自动推送视频
									rMap = solrServerClient.doRecommend(lable.toString(), "0", 1, 1, false) ;
									solrList = (List<SolrEntity>) rMap.get("rows") ;
									if(solrList!= null && solrList.size() > 0){
										smsType = SmsTypeEnum.VIDEO_ANSWER.getSmsType() ;
										SolrEntity se = solrList.get(0);
										if(se != null){
											MessageUtils.videoMessageTemp(se, messageList);
										}
									}else{//没有视频就推送明师主页
										//暂时
										rMap = solrServerClient.doRecommend("大山笑长", "1", 1, 1, false) ;
										solrList = (List<SolrEntity>) rMap.get("rows") ;
										if(solrList!= null && solrList.size() > 0){
											smsType = SmsTypeEnum.TEACER_ANSWER.getSmsType() ;
											SolrEntity se = solrList.get(0);
											if(se != null){
												MessageUtils.teacherMessageTemp(se, messageList);
											}
										}
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else if("2".equals(smsType)){//推送视频
							try {
								Map<String, Object>	rMap = solrServerClient.doRecommend(lable.toString(), "0", 1, 1, false) ;
								List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
								if(solrList!= null && solrList.size() > 0){
									smsType = SmsTypeEnum.VIDEO_ANSWER.getSmsType() ;
									SolrEntity se = solrList.get(0);
									if(se != null){
										MessageUtils.videoMessageTemp(se, messageList);
									}
								}else{//没有视频就推送明师主页
									//暂时
									rMap = solrServerClient.doRecommend("大山笑长", "1", 1, 1, false) ;
									solrList = (List<SolrEntity>) rMap.get("rows") ;
									if(solrList!= null && solrList.size() > 0){
										smsType = SmsTypeEnum.TEACER_ANSWER.getSmsType() ;
										SolrEntity se = solrList.get(0);
										if(se != null){
											MessageUtils.teacherMessageTemp(se, messageList);
										}
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else if("3".equals(smsType)){//推送明师主页
							try {
								Map<String, Object> rMap = solrServerClient.doRecommend("大山笑长", "1", 1, 1, false) ;
								List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
								if(solrList!= null && solrList.size() > 0){
									smsType = SmsTypeEnum.TEACER_ANSWER.getSmsType() ;
									SolrEntity se = solrList.get(0);
									if(se != null){
										MessageUtils.teacherMessageTemp(se, messageList);
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else{
							MessageUtils.textMessage(StringUtils.isBlank(content)== true ? "不好意思，你说的问题我听不懂，请直接提问我们的专家老师，感谢你的咨询，再见！" : content
									, keywords, SmsTypeEnum.SYS_ANSWER.getSmsType(), messageList);
						}
					}else {//smsType没有值 是从科大讯飞云函数返回来的
						MessageUtils.textMessage(content , keywords, SmsTypeEnum.TEXT_ANSWER.getSmsType(), messageList);
					}
				}
				
				map.put("data", messageList) ;
				map.put("smsType", smsType) ;
				map.put("err_code", "200") ; 
				map.put("err_msg", "请求成功");
				map.put("sessionId", sessionId);
				
			}else{ // 其他的科大讯飞技能
				if(answer != null){
					content = answer.getString("text") ;
				}
				MessageUtils.textMessage(content , keywords, SmsTypeEnum.TEXT_ANSWER.getSmsType(), messageList);
				
				map.put("data", messageList) ;
				map.put("smsType", SmsTypeEnum.TEXT_ANSWER.getSmsType()) ;
				map.put("err_code", "200") ; 
				map.put("err_msg", "请求成功");
				map.put("sessionId", sessionId);
			}
			
		}else if("4".equals(baseObj.get("rc").toString())){//识别不到语义，这里自定义
			try {
				Map<String, Object> rMap = solrServerClient.doRecommend2(txt, 1, 1, false) ;
				List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
				if(solrList!= null && solrList.size() > 0){
					SolrEntity se = solrList.get(0);
					if(se != null){
						MessageUtils.textMessage("这是与您相关问题的回答，希望能帮到您", null, SmsTypeEnum.SYS_ANSWER.getSmsType(), messageList);
						
						if(se.getId().indexOf("questionComment_")!=-1){//回答(文字和语音)
							if(StringUtils.isNotBlank(se.getRecordName())){//语音回答
								MessageUtils.audioMessage(se.getRecordName(), se.getRecordDuration(), messageList);
							}else{//文字回答\
								MessageUtils.textMessage(se.getCommentContent(), null, SmsTypeEnum.TEXT_ANSWER.getSmsType(), messageList);
							}
						}else if(se.getId().indexOf("video_")!=-1){//视频
							MessageUtils.videoMessage(se.getVideoName(), se.getVideoId(), se.getCoverUrl(), messageList);
						}
						MessageUtils.textMessage("如果您需要更加精准的问题，点击我的头像，众多“明师”坐等解决您的家庭难题。", null, SmsTypeEnum.SYS_ANSWER.getSmsType(), messageList);
					}
				}else{
					Map<String, Object> rMap1 = solrServerClient.doRecommend("大山笑长", "1", 1, 1, false) ;
					List<SolrEntity> solrList1 = (List<SolrEntity>) rMap1.get("rows") ;
					if(solrList1!= null && solrList1.size() > 0){
						SolrEntity se = solrList1.get(0);
						if(se != null){
							MessageUtils.teacherMessageTemp(se, messageList);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			map.put("data", messageList) ;
			map.put("err_code", "200") ; 
			map.put("err_msg", "请求成功");
			map.put("smsType", smsType) ;
			map.put("sessionId", sessionId);
			
		}else { // 1,2,3	
			map.put("data", messageList) ;
			map.put("err_code", jsonObj.get("code")) ; 
			map.put("err_msg", jsonObj.get("desc")) ;
			map.put("smsType", smsType) ;
			map.put("sessionId", sessionId);
		}
		//插入回复的信息 
		if(messageList != null && messageList.size() > 0){
			int count = 0 ;
			for(ChatMessageDTO chat : messageList){
				//记录用户的回答记录
				AiuiRecordInfo answerInfo = new AiuiRecordInfo() ;
				answerInfo.setUserId(aInfo.getUserId());
				answerInfo.setCreateTime(new Timestamp(System.currentTimeMillis()+ (++count)*1000) );
				answerInfo.setContent(chat.getContent());
				answerInfo.setSmsType(chat.getSmsType());
				answerInfo.setAnswerId(aInfo.getId());
				answerInfo.setKeywords(chat.getKeywords());
				answerInfo.setRid(chat.getRid());
				answerInfo.setPicUrl(chat.getPicUrl());
				answerInfo.setAudioUrl(chat.getAudioUrl());
				answerInfo.setDuration(chat.getDuration());
				answerInfo.setSessionId(sessionId);
				//插入回复信息记录
				aiuiRecordInfoDao.insert(answerInfo);
				
			}
		}
		
		
		return map;
	}

	@Override
	public Object getChatHistory(AiuiRecordInfoDTO dto) {
		Map<String , Object> map = new HashMap<String, Object>() ;
		if(dto.getUserId() == null){
			map.put("err_code", "100");
			map.put("err_msg", "用户id为空");
			return map ;
		}
		List<AiuiRecordInfoDTO> list = aiuiRecordInfoDao.getChatHistory(dto) ;
		if(null != list && list.size() > 0 ){
			map.put("err_code", "200") ;
			map.put("err_msg", "查询成功") ;
			map.put("data", list) ;
		}else{
			map.put("err_code", "400") ;
			map.put("err_msg", "查询成功,无数据") ;
			map.put("data", null) ;
		}
		return map;
	}

	@Override
	public Object getTeacherList(TeacherInfoDTO dto) {
		Map<String , Object> map = new HashMap<String , Object>() ;
		try {
			Map<String, Object> rMap = solrServerClient.doRecommend(null, "11", dto.getPageStart(), dto.getRows(), false);
			List<SolrEntity> solrList = (List<SolrEntity>) rMap.get("rows") ;
			if(solrList !=null && solrList.size() > 0 ){
				map.put("err_code", 0);
				map.put("err_msg", "查询有数据");
				map.put("rows", solrList) ;
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "查询无数据");
				map.put("rows", null) ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return map ;
	}

}
